package com.chezai.client.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.text.TextUtils;
import android.view.Surface;
import android.view.WindowManager;

import com.baidu.idl.face.platform.utils.APIUtils;
import com.chezai.client.activitys.C703BCameraActivity;
import com.chezai.client.activitys.Camera2Activity;
import com.chezai.client.global.Const;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.global.location.LocationMgr;
import com.orhanobut.logger.Logger;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Describe 拍照工具类
 * Created by LKY on 2016/11/9.
 */
public class CameraMgr {

    public static void startFaceCamera(Context from, String uid, int photoEventType
            , int trainPart
            , String studentName
            , String coachName
            , Long classRecordId) {
        if (AppManager.getAppManager().isOpenActivity(Camera2Activity.class)) return;
        Intent intent;

        String s = TerminalApplication.channelModel;
        if (from == null) {
            intent = new Intent(TerminalApplication.mContext, Const.QHYC_C103.equals(TerminalApplication.channelModel) ? Camera2Activity.class : C703BCameraActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            intent = new Intent(from, Const.QHYC_C103.equals(TerminalApplication.channelModel) ? Camera2Activity.class : C703BCameraActivity.class);
        }
        intent.putExtra(Const.EVENT_PHOTO_TYPE, photoEventType);
        intent.putExtra(Const.TRAIN_PART, trainPart);
        intent.putExtra(Const.STUDENT_UID, uid);
        if (!TextUtils.isEmpty(studentName)) {
            intent.putExtra(Const.STUDENT_NAME, studentName);
        }
        if (!TextUtils.isEmpty(coachName)) {
            intent.putExtra(Const.COACH_NAME, coachName);
        }
        if (classRecordId != null) {
            intent.putExtra(Const.CLASS_RECORD_ID, classRecordId);
        }
        if (from == null) {
            TerminalApplication.mContext.startActivity(intent);
        } else {
            from.startActivity(intent);
        }

    }

    /**
     * 判断相机是否可用
     *
     * @return
     */
    public static boolean cameraIsCanUsed() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open(1);
            Camera.Parameters parameters = mCamera.getParameters();// 获取相机参数集
            mCamera.setParameters(parameters);
        } catch (Exception e) {
            isCanUse = false;
        }
        if (null != mCamera) {
            mCamera.release();
        }
        return isCanUse;
    }

    /**
     * 获取摄像头预览尺寸
     *
     * @param sizes
     * @param w
     * @param h
     * @return
     */
    public static Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    /**
     * 旋转图片
     *
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static int[] setCameraDisplayOrientation(Context ctx, int paramInt) throws RuntimeException {
        try {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(paramInt, info);
            int rotation = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();  //获得显示器件角度
            int degrees = 0;
            switch (rotation) {
                case Surface.ROTATION_0:
                    degrees = 0;
                    break;
                case Surface.ROTATION_90:
                    degrees = 90;
                    break;
                case Surface.ROTATION_180:
                    degrees = 180;
                    break;
                case Surface.ROTATION_270:
                    degrees = 270;
                    break;
            }
            int orientationOfCamera = info.orientation;
            int[] result = new int[2];
            result[0] = orientationOfCamera;      //获得摄像头的安装旋转角度
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                result[1] = (orientationOfCamera + degrees) % 360;
                result[1] = (360 - result[1]) % 360;  // compensate the mirror
            } else {  // back-facing
                result[1] = (orientationOfCamera - degrees + 360) % 360;
            }
            return result;
        } catch (RuntimeException e) {
            throw e;
        }
    }

    public static int displayOrientation(int mCameraId, Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int rotation = windowManager.getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
            default:
                degrees = 0;
                break;
        }
        int result = (0 - degrees + 360) % 360;
        if (APIUtils.hasGingerbread()) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(mCameraId, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                result = (info.orientation + degrees) % 360;
                result = (360 - result) % 360;
            } else {
                result = (info.orientation - degrees + 360) % 360;
            }
        }
        return result;
    }

    /**
     * 添加水印
     *
     * @param bitmap
     * @return
     */
    public static Bitmap onWaterDraw(Bitmap bitmap, int trainPart, String studentName, String coachName,long timeStamp) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        int margen = 10;
        float textSize = 20;
        Rect src = new Rect(0, 0, w, h);
        Rect dst = new Rect(0, 0, w, h);
        Bitmap tempBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        Canvas canvas = new Canvas(tempBitmap);
        canvas.drawBitmap(bitmap, src, dst, paint);
        paint.setColor(Color.RED);
        paint.setTextSize(textSize);
        canvas.drawText("车牌照：" + Const.CAR_CODE, margen, textSize, paint);
        canvas.drawText("驾校名称：" + Const.SCHOOL_NAME, margen, 2 * textSize, paint);
        canvas.drawText("速度：" + LocationUtils.conversionSpeedKmH(LocationMgr.getInstance().getSpeed() * 10), margen, h - 2 * textSize - margen, paint);
        canvas.drawText("经度：" + LocationMgr.getInstance().getCurrentLat(), margen, h - 1 * textSize - margen, paint);
        canvas.drawText("纬度：" + LocationMgr.getInstance().getCurrentLon(), margen, h - 0 * textSize - margen, paint);
        //右上角
        String time = DateUtil.timestampStr7(timeStamp);
        float length = paint.measureText(time);
        canvas.drawText(time, w - length - margen, textSize, paint);
        //右下角
        String trainPartStr = "培训部分：" + (trainPart == 1 ? "第一部分" : trainPart == 2 ? "第二部分" : trainPart == 3 ? "第三部分" : trainPart == 4 ? "第四部分" : "");
        float trainLength = paint.measureText(trainPartStr);
        String studentNameStr = "学员姓名：" + studentName;
        float studentNameLength = paint.measureText(studentNameStr);
        String coachNameStr = "教练姓名：" + coachName;
        float coachNameLength = paint.measureText(coachNameStr);
        canvas.drawText(trainPartStr, w - trainLength - margen, h - 2 * textSize - 10 - margen, paint);
        canvas.drawText(studentNameStr, w - studentNameLength - margen, h - 1 * textSize - 5 - margen, paint);
        canvas.drawText(coachNameStr, w - coachNameLength - margen, h - 0 * textSize - margen, paint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return tempBitmap;
    }

    /**
     * 保存bitmap
     *
     * @param bitmap   图片源
     * @param filePath 保存地址
     * @return 是否成功
     */
    public static boolean saveBitmapToFile(Bitmap bitmap, String filePath) {
        BufferedOutputStream bos = null;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int quality = 70;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);// 将图片压缩的流里面
            bos.flush();// 刷新此缓冲区的输出流
            bos.close();// 关闭此输出流并释放与此流有关的所有系统资源
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            FileUtil.closeIO(bos);
        }

    }


    public static Bitmap copyBitmap(Bitmap bitmap, Rect src) {
        int tempW = src.right - src.left;
        int tempH = src.bottom - src.top;
        Rect dst = new Rect(0, 0, tempW, tempH);
        Bitmap tempBitmap = Bitmap.createBitmap(tempW, tempH, Bitmap.Config.RGB_565);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        Canvas canvas = new Canvas(tempBitmap);
        canvas.drawBitmap(bitmap, src, dst, paint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return tempBitmap;
    }

    public static Rect switchRect(int viewW, int viewH, int picW, int picH, Rect detectRect) {

        if (viewW == 0 || viewH == 0 || picW == 0 || picH == 0) {
            return null;
        }
        float scaleL = detectRect.left * 1.0f / viewW;
        float scaleT = detectRect.top * 1.0f / viewH;
        int w = detectRect.right - detectRect.left;
        int h = detectRect.bottom - detectRect.top;
        float scaleW = w * 1.0f / viewW;
        float scaleH = h * 1.0f / viewH;
        int newW = (int) (picW * scaleW + 0.5f);
        int newH = (int) (picH * scaleH + 0.5f);
        Rect rect = new Rect();
        rect.left = (int) (picW * scaleL + 0.5f);
        rect.top = (int) (picH * scaleT + 0.5f);
        rect.right = rect.left + newW;
        rect.bottom = rect.top + newH;
        Logger.t("SwitchRect").d("scaleL:" + scaleL + " scaleT:" + scaleT + " w:" + w +
                " newW:" + newW + " detectRect:" + detectRect.toShortString() + " newRect:" + rect.toShortString());
        return rect;
    }


}
